import { window, workspace } from "vscode";
import * as stringWidth from "string-width";

/**
 * 将用户输入的基金代码更新到配置中
 * @param codeList
 */
export async function updateFund(codeList: string[]): Promise<void> {
  const config = workspace.getConfiguration();
  const defaultFundList: string[] = config.get("fund-watch.favorites", []);
  const newCodeList: string[] = codeList.filter((item) => !!item);
  // 去重，避免用户输入了已经存在的基金代码
  const newFundList = Array.from(new Set([...defaultFundList, ...newCodeList]));
  // 这里要await，因为 config.update 是个异步操作
  await config.update("fund-watch.favorites", newFundList, true);
}

/**
 * 删除对应的自选基金
 * @param code
 */
export function removeFund(code: string): void {
  const config = workspace.getConfiguration();
  const defaultFundList: string[] = config.get("fund-watch.favorites", []);
  const index = defaultFundList.indexOf(code);
  if (index > -1) {
    defaultFundList.splice(index, 1);
    config.update("fund-watch.favorites", defaultFundList, true);
  }
}

/**
 * 给字符串填充空格至指定长度，如果超长，就截掉
 * @param source
 * @param length
 * @param left
 * @returns
 */
export function fillString(
  source: string,
  length: number,
  left = true
): string {
  let rest = source;
  while (stringWidth(rest) >= length) {
    rest = rest.slice(0, rest.length - 1);
  }
  const addString = "  ".repeat(length - stringWidth(rest));
  return left ? `${rest}${addString}` : `${addString}${rest}`;
}

export function showInfomationMesage(): void {
  const nowDate = new Date();
  const hours = nowDate.getHours();
  const minutes = nowDate.getMinutes();
  const tips = [
    "靓仔，睇下宜家几时啦",
    "靓仔，仲唔加仓？",
    "-----------------------",
    "7头，唔系做啦，做咁多，可以发过猪肉荣吗？",
  ];
  let time: number = 0;
  if (hours < 14 || (hours === 14 && minutes <= 55)) {
    time = ((14 - hours) * 60 - minutes + 55) * 60 * 1000;
  }
  if (hours > 14) {
    time = ((hours - 14) * 60 + minutes - 55) * 60 * 1000;
  }
  setTimeout(() => {
    window.showInformationMessage(tips.join("\r\n"));
    setInterval(() => {
      window.showInformationMessage(tips.join("\r\n"));
    }, 86400000);
  }, time);
}
